import { ElMessage } from 'element-plus'
import axios, { type AxiosResponse, type InternalAxiosRequestConfig, type AxiosError } from 'axios'

const service = axios.create({
  timeout: 60000,
  withCredentials: true
})

service.interceptors.response.use((response: AxiosResponse<any>) => {
  // todo 文件下载
  if (response.headers['content-disposition'] && response.headers['content-disposition'].includes('attachment')) {
    return Promise.resolve(response)
  }
  if (response.data.code !== '0') {
    response.data.message && ElMessage.error(response.data.message)
    return Promise.reject(response)
  }

  return Promise.resolve(response.data.data)
}, function (error: any) {
  if (error?.response?.status === 401) {
    localStorage.clear()
    location.href = location.origin + import.meta.env.VITE_APP_BASE_URL + '/login'
    return
  }
  const errmsg = error.response?.data?.message || error.message || '网络连接异常'
  ElMessage.error(errmsg)
  return Promise.reject(error.response)
})

service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.accesstoken = token
  }
  // todo
  return config
}, function (error: AxiosError): Promise<AxiosError> {
  return Promise.reject(error)
})

export default service
